﻿using MediatR;
using Sale.Api.Application.Command.Client;
using Sale.Domain;
using Sale.Dtos;
using Sale.ErrorCode;
using Sale.Infrastructure.Interface;

namespace Sale.Api.Application.Handler.Client
{
    public class GetClientHandler : IRequestHandler<GetClientCommand, ApiPaging<ClientDTO>>
    {
        private readonly IBaseRepository<ClientModel> clientRepo;
        private readonly ILogger<GetClientHandler> logger;
        private readonly IBaseRepository<CTypeModel> cTypeRepo;

        public GetClientHandler(IBaseRepository<ClientModel> clientRepo,ILogger<GetClientHandler> logger,IBaseRepository<CTypeModel> cTypeRepo)
        {
            this.clientRepo = clientRepo;
            this.logger = logger;
            this.cTypeRepo = cTypeRepo;
        }
        public Task<ApiPaging<ClientDTO>> Handle(GetClientCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<ClientDTO> paging = new ApiPaging<ClientDTO>();
            var client = clientRepo.GetAll().Where(x=>x.IsDel==false);
            var CType = cTypeRepo.GetAll();
            if(!string.IsNullOrEmpty(request.ClientName))
            {
                client = client.Where(x => x.ClientName.Contains(request.ClientName));
            }
            var linq = from a in client
                       join b in CType
                       on a.CTypeId equals b.CTypeId
                       select new ClientDTO
                       {
                           ClientTel=a.ClientTel,
                           CTypeId=b.CTypeId,
                           ClientCode =a.ClientCode,
                           ClientName =a.ClientName,
                           ClientState =a.ClientState,
                           ClientContact =a.ClientContact,
                           ClientId =a.ClientId,
                           ClientRemark =a.ClientRemark,
                           CTypeName=b.CTypeName,
                       };
            paging.Msg = "客户显示成功";
            paging.Data = linq.ToList();
            paging.Code = ApiEnum.OK;
            logger.LogInformation(paging.Msg);
            return Task.FromResult(paging);
        }
    }
}
